package Controllers;

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import Boundry.AddNewEmployeGUI;
import Boundry.AddNewInfoSys;
import Boundry.CloseRequestPanel;
import Boundry.InitTaskPanel;
import Boundry.NominateCommitteeAndInspectorPanel;
import Boundry.ResumeRequestPanel;
import Boundry.SatisticalReportPanel;
import Boundry.ShowWorkersPanel;
import Boundry.ViewReuestDataPanel;
import Boundry.ViewReuestsTableListPanel;
import Boundry.ViewReuestsTablePanel;
import Boundry.Waiting;
import Boundry.WorkerPanel;
import Boundry.GenericTools.RequestTableListPanel;
import Controllers.GenericToolsForController.BaseClass;
import Controllers.GenericToolsForController.PDFDocument;
import Controllers.GenericToolsForController.PDFfile;
import Controllers.GenericToolsForController.RequestMainStatusEnum;
import Controllers.GenericToolsForController.RequestStepStatusEnum;
import Controllers.GenericToolsForController.WorkerRolls;
import Entity.ActivityReport;
import Entity.DelayReport;
import Entity.InfoSystem;
import Entity.OperationReport;
import Entity.Report;
import Entity.Request;
import Entity.RequestStatusHistory;
import Entity.Status;
import Entity.User;
import Entity.Worker;

public class ICMManagerController extends BaseClass implements ItemListener 
{
	
	private RequestTableListPanel resumeRequestTableListPanel; //for Closing Stap
	private ResumeRequestPanel resumeRequestPanel;
	
	private RequestTableListPanel unnominateCommAndInspRequestTableListPanel;  //  for  nominate comm and inspector step
	private NominateCommitteeAndInspectorPanel nominateComAndInsPane;
	
	private ViewReuestsTablePanel viewReuestsTablePanel;  //for Closing Stap
	private ViewReuestDataPanel viewReuestDataPanel;
	private int closeReqTab=0,openReqTab=1,suspendReqTab=2;
	
	
	private ShowWorkersPanel showWorkersPanel;
	
	
	private AddNewEmployeGUI addworkerscreen; // adding new worker
	private AddNewInfoSys addNewInfoSysPanel;
	private NominateCommitteeAndInspectorPanel nominatePanel; //nominate panel 
	
	
	private  List<Worker> workerlist;
	private  ArrayList<User> UsersNonworkerlist;
	private  List<Request> requestlist;
	
	private  List<Request> requestCloselist;
	private  List<Request> requestOpenlist;
	private List<Request> requestSuspendedlist;
	
	private List<Worker> workers;
	private List<Worker> workersIE;
	private Object selcted1,selcted2,selcted3;
	private ArrayList<Request> requestsToNominate;
	private Request chosenReq;
	private Worker chosenWorker;
	private ArrayList<Request> requestsToreNominate;
	
	List<Report> allActivityReport ;
	Waiting waitScreen;
	private SatisticalReportPanel statisticalReportPanel;
	private int days;
	private int daysInLookBack = 30;
	/*
	 * Singleton 
	 */
	private static  ICMManagerController Instance = null;
	private ICMManagerController(){}
	public static ICMManagerController getInstance()
	{
		if(Instance == null)
		{
			Instance = new ICMManagerController();
		}
		return Instance;
	}
	
	/**
	 * @author Shimon Arzuan
	 * Resume Request : get from DB all request that are in "Suspend" status
	 * the icm manager chose on request to resume.
	 * @return
	 */
	public void resumeRequest() //shimon
	{	
		waitScreen = new Waiting();
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {				
				try {
					requestlist = RequestManager.getInstance().getAllSuspendedRequests();
					System.out.println("There is a -" + requestlist.size() + " Of Suspended Request");
					//Build table for the Suspended request list.
					if(requestlist.size()>0)
					{
						tableData =  new String[requestlist.size()][requestlist.get(0).dataToStringArray().length];
						for(int i=0; i<tableData.length ; i++)
						{
							tableData[i] = requestlist.get(i).dataToStringArray();
						}
						columnNames = requestlist.get(0).indexStringArray();
						
						
						resumeRequestTableListPanel = new RequestTableListPanel();
						GlobalData.guiMangaer.switchScreen(resumeRequestTableListPanel);
						resumeRequestTableListPanel.buildTabel(columnNames,tableData);
						setListenerToViewDataPanel(resumeRequestTableListPanel);	
					}
					else
					{
						waitScreen.kill();
						JOptionPane.showMessageDialog(new JFrame(),"There is not request Suspended", "",JOptionPane.DEFAULT_OPTION);
					}
				} catch (HeadlessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					JOptionPane.showMessageDialog(new JFrame(),"There is a problem Suspended the requesr", "",JOptionPane.DEFAULT_OPTION);
				}
				return null;
			}
			@Override
			public void done() 
			{
				waitScreen.kill();
				waitScreen=null;
			}
		    };  
			worker.execute();
		
		
	}
	
	/**
	 * @author Shimon Arzuan
	 * add new info system to the system.
	 * @return
	 */
	public void addNewInfoSystem()  
	{
		addNewInfoSysPanel = new AddNewInfoSys();
		setListenerToInputPanel(addNewInfoSysPanel);	
		
		SwingWorker worker = new SwingWorker<Void, Void>() {
		@Override
		 public Void doInBackground() 
		 {
			//System.out.println("");
			System.out.println("  WorkerManager.getInstance().getIEWorkers(); ");
			workerlist = WorkerManager.getInstance().getIEWorkers();
			System.out.println(workerlist.get(0).getFirstName());
			System.out.println("before swith");
			GlobalData.guiMangaer.switchScreen(addNewInfoSysPanel);
			System.out.println("after");
			tableData =  new String[workerlist.size()][workerlist.get(0).dataToStringArray().length];

			for(int i=0; i<tableData.length ; i++)
			{
				tableData[i] = workerlist.get(i).dataToStringArray();
			}
			columnNames = workerlist.get(0).indexStringArray();
			
			addNewInfoSysPanel.buildTabel(columnNames,tableData);
			return null;
		}
		@Override
		public void done() 
		{
			
		}
	    };  
		worker.execute();	
	}
	
	

	public void addNewWorker()
	{
		//TODO need to be implemented
		 addworkerscreen = new AddNewEmployeGUI();
		setListenerToInputPanel(addworkerscreen);
		
		UsersNonworkerlist = UsersManager.getInstance().getAllUsersNonWorkers();
		if (UsersNonworkerlist==null){
			JOptionPane.showMessageDialog(new JFrame(),"There are no users in the database aviable for manipulation", "",JOptionPane.DEFAULT_OPTION);
			return;
		}
		addworkerscreen.getComboBoxUserDetails().addItemListener(this);
		//addworkerscreen.getBtnTakeImage().addActionListener(this);
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {
				
				int i=0;
				for (User user : UsersNonworkerlist){
					if (i==0){
						i++;
						addworkerscreen.setTextTotextFieldID(""+user.getUserId());
					}
					//System.out.println("whyyyyy?");
					addworkerscreen.addItemTocomboBoxUserDetails(""+user.getUserId() +") "+user.getFirstName() +" "+user.getLastName());
					System.out.println(""+user.getUserId() +") "+user.getFirstName() +" "+user.getLastName());
				}
				
			//	System.out.println("whyyyyy?");
				
				return null;
			 }
			public void done(){
				GlobalData.guiMangaer.switchScreen(addworkerscreen);
			}
		};
		worker.execute();	
		//addworkerscreen.getComboBoxUserDetails().addActionListener(this);
		
	/*	addworkerscreen.getComboBoxUserDetails().addPropertyChangeListener(new PropertyChangeListener(){

			@Override
			public void propertyChange(PropertyChangeEvent e) {
				// TODO Auto-generated method stub
				String id = (String) addworkerscreen.getComboBoxUserDetails().getSelectedItem();
				//String[] sid = id.split(")");
				System.out.println("Chaged");
				addworkerscreen.setTextTotextFieldID(id);
			}
			
			
			
		});*/
		
		
		
		
		
		
		
		System.out.println("addNewWorker not implemented");
	}
	
	
	/**
	 * @author Shimon Arzuan
	 * this function opetate the view requests of the icm manager
	 * @return
	 */
	public void showAllRequests()
	{
		waitScreen = new Waiting();
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {	
				
				System.out.println("  Get All Request : Close,Open,Suspend By Inspector ");
				
				requestCloselist  = RequestManager.getInstance().getAllCloseRequests();
				requestOpenlist = RequestManager.getInstance().getAllOpenRequests();
				requestSuspendedlist = RequestManager.getInstance().getAllSuspendedRequests();
				
				System.out.println("requestSuspendedlist:" + requestSuspendedlist.size() + "requestOpenlist: " +	requestOpenlist.size()
						+ "requestCloselist : " + requestCloselist.size()
						);
				//Build table for the Suspended request list.
				if( requestCloselist==null && requestOpenlist==null && requestSuspendedlist==null)			 
				{
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is not request for Inspector", "",JOptionPane.DEFAULT_OPTION);
				}
				else
				{
					try 
					{
						viewReuestsTablePanel =  new ViewReuestsTablePanel(3);
						viewReuestsTablePanel.buildTabPanel();
						GlobalData.guiMangaer.switchScreen(viewReuestsTablePanel);
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
									
					try {
						
						//Close Req
						if(requestCloselist!=null && requestCloselist.size()>0)
						{
							tableData =  new String[requestCloselist.size()][requestCloselist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestCloselist.get(i).dataToStringArray();
							}
							columnNames = requestCloselist.get(0).indexStringArray();
							System.out.println("There is request Close list " + requestCloselist.size() );
							viewReuestsTablePanel.buildTabI(closeReqTab,"Closed Requests","Close Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(closeReqTab,"Closed Requests","Close Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not requestCloselist");
						}
						
						
						
						// Open Req
						if(requestOpenlist!=null && requestOpenlist.size()>0)
						{
							tableData =  new String[requestOpenlist.size()][requestOpenlist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestOpenlist.get(i).dataToStringArray();
							}
							columnNames = requestOpenlist.get(0).indexStringArray();
							
							System.out.println("There is openReq " + requestOpenlist.size() );
							
							viewReuestsTablePanel.buildTabI(openReqTab,"Open Requests","Open Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(openReqTab,"Open Requests","Open Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not openReqTab");
						}
						
						
						
						//suspend ReqrequestOpenlist
						if(requestSuspendedlist!=null && requestSuspendedlist.size()>0)
						{
							tableData =  new String[requestSuspendedlist.size()][requestSuspendedlist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestSuspendedlist.get(i).dataToStringArray();
							}
							columnNames = requestSuspendedlist.get(0).indexStringArray();
							System.out.println("There is request Suspended list " + requestSuspendedlist.size() );
							viewReuestsTablePanel.buildTabI(suspendReqTab,"Suspend Requests","Suspend Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(suspendReqTab,"Suspend Requests","Suspend Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not suspendReqTab");
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
		
					setListenerToViewDataPanel(viewReuestsTablePanel);	
				}
				return null;
			 }
			@Override
			public void done() 
			{
				waitScreen.kill();
				waitScreen=null;
			}
			};  
			worker.execute();
		
		System.out.println("showAllRequests not implemented");
		
	}
	
	
	public void showAllWorkers()
	{
		waitScreen = new Waiting();
		//showWorkersPanel
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {				
				try {
					workerlist = WorkerManager.getInstance().getAllWorkers();
					System.out.println("There is a -" + workerlist.size() + " Of Worker");
					//Build table for the Suspended request list.
					if(workerlist.size()>0)
					{
						tableData =  new String[workerlist.size()][workerlist.get(0).dataToStringArray().length];

						for(int i=0; i<tableData.length ; i++)
						{
							String id = workerlist.get(i).getId() +"";
							String userName = workerlist.get(i).getUsername();
							tableData[i] = new String[]{id,userName};
						}
						columnNames =  new String[]{"Worker Id","Worker UserName"};
						
						
						showWorkersPanel = new ShowWorkersPanel();
						GlobalData.guiMangaer.switchScreen(showWorkersPanel);
						showWorkersPanel.buildTabel(columnNames,tableData);
						setListenerToInputPanel(showWorkersPanel);	
						
						ListSelectionModel cellSelectionModel = showWorkersPanel.getCellSelectionModel();    
						cellSelectionModel.addListSelectionListener(new ListSelectionListener() 
						    {
								@Override
								public void valueChanged(ListSelectionEvent e) 
								{
									int row =showWorkersPanel.getTable().getSelectedRow();
									chosenWorker = workerlist.get(row);
									showWorkersPanel.setWorkerName(chosenWorker.getFirstName() +" " +chosenWorker.getLastName());
									showWorkersPanel.setEmail(chosenWorker.getEmail());
									showWorkersPanel.setPhone(chosenWorker.getPhone());
									showWorkersPanel.setRole(chosenWorker.getRole().toString());
									
								}
							
						  });
					}
					else
					{
						waitScreen.kill();
						JOptionPane.showMessageDialog(new JFrame(),"There is not Worker In System", "",JOptionPane.DEFAULT_OPTION);
					}
				} catch (HeadlessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is a problem", "",JOptionPane.DEFAULT_OPTION);
				}
				return null;
			}
			@Override
			public void done() 
			{
				waitScreen.kill();	
				waitScreen=null;
			}
		    };  
			worker.execute();
	}
	
	
	
	
	
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		// TODO Auto-generated method stub

		/*
		 * add new worker
		 */
		addWorkerListener(e); 
		/* 
		 * Resume Request Handle Listener
		 */
		resumeRequestListener(e);
		/*
		 * addNewInfoSystem  Handle Listener
		 */
		addNewInfoSystemListener(e);
		/*
		 * nominate  Handle Listener
		 */
		nominateListener(e);
		/*
		 * ViewRequest  Handle Listener
		 */
		ViewRequestListener(e);
		
		showWorkersPanelListener(e);
		
		statisticalReportsListener(e);
		
	}
	
	
	private void statisticalReportsListener(ActionEvent e)
	{
		System.out.println("Action listener in ICMManager");
		if (statisticalReportPanel != null)
		{
			if (e.getSource() == statisticalReportPanel.getBtnActivityReport() )
			{
				Report activity = ReportManager.getInstance().getActivityReport(statisticalReportPanel.getDateFrom(), statisticalReportPanel.getDateTo());
				if (activity != null)
				{
					activity.getPdfFile().write("Activity Report.pdf");
					PDFDocument docOpener = new PDFDocument("Activity Report.pdf");
				}
			}
			if (e.getSource() == statisticalReportPanel.getBtnDelayReport() )
			{
				Date daysAgo = new Date(new Date().getTime()-1000*60*60*24*daysInLookBack );
				Report delay = ReportManager.getInstance().getDelayReport(daysAgo, new Date());
				if (delay != null)
				{
					delay.getPdfFile().write("delay Report.pdf");
					PDFDocument docOpener = new PDFDocument("delay Report.pdf");
				}
			}
			
			if (e.getSource() == statisticalReportPanel.getBtnOpreationReport() )
			{
				Date daysAgo = new Date(new Date().getTime()-1000*60*60*24*daysInLookBack );
				Report operation = ReportManager.getInstance().getOperationReport(daysAgo, new Date());
				if (operation != null)
				{
					operation.getPdfFile().write("Opreation Report.pdf");
					PDFDocument docOpener = new PDFDocument("Opreation Report.pdf");
				}
			}
			if (e.getSource() == statisticalReportPanel.getBtnDisplayPastReports() )
			{
				if (statisticalReportPanel.getComboBoxPastReports().getSelectedItem() instanceof String )
				{
					String comment = (String) statisticalReportPanel.getComboBoxPastReports().getSelectedItem();
				{
					
					for (Report activity : allActivityReport ) 
						{
						     if (comment.equals(activity.getComment()))
						    		 {
						    	      activity.getPdfFile().write("Activity.PDF");
						    	      PDFDocument docOpener = new PDFDocument("Activity.PDF");
						    		 }
						}
					;
				}
			}
				
		}
			if (e.getSource() == statisticalReportPanel.btnBack )
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);

			}
		}
		else
		{
			System.out.println("statistic panel is null");

		}
		
		
		
		
	}
	
	
	
	
	
	private void showWorkersPanelListener(ActionEvent e) {
		if(showWorkersPanel!=null)
		{
			if (e.getSource() == showWorkersPanel.btnBack)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == showWorkersPanel.btnSubnit)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
		}
	}
	/**
	 * @param e
	 */
	private void ViewRequestListener(ActionEvent e)
	{
		System.out.println("ViewRequestListener");
		if(viewReuestsTablePanel != null)
		{
			if (e.getSource() == viewReuestsTablePanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == viewReuestsTablePanel.btnNext)
			{	
				if(viewReuestsTablePanel.isChosen())
				{
					int i = viewReuestsTablePanel.getChosen();
					
					Request req;
					int tab = viewReuestsTablePanel.getChooseTab();

					if(tab==closeReqTab)
					{
						chosenReq = requestCloselist.get(i);
					}
					else if(tab==openReqTab)
					{
						chosenReq = requestOpenlist.get(i);
					}
					else if(tab==suspendReqTab)
					{
						chosenReq = requestSuspendedlist.get(i);
					}
					
					viewReuestDataPanel = new ViewReuestDataPanel();
					GlobalData.guiMangaer.switchScreen(viewReuestDataPanel);
					
					viewReuestDataPanel.setDateOfCreation(chosenReq.getDate().toString());
					viewReuestDataPanel.setInfoSystemName(chosenReq.getInfoSystem().getName());
					viewReuestDataPanel.setInitatorName(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
					viewReuestDataPanel.setCurrentState(chosenReq.getCurrentState());
					viewReuestDataPanel.setProposedChangs(chosenReq.getDescription());
					viewReuestDataPanel.setExcuse(chosenReq.getExecuse());
					viewReuestDataPanel.setNote(chosenReq.getNotes());
					
					List<RequestStatusHistory> historyList = chosenReq.getHistory();
					System.out.println(" historyList.size() : " + historyList.size());
					
					//Build table for the History Of the request list.
					tableData =  new String[historyList.size()][historyList.get(0).dataToStringArray().length];
					for(int j=0; j<tableData.length ; j++)
					{
						tableData[j] = historyList.get(j).dataToStringArray();
					}
					columnNames = historyList.get(0).indexStringArray();
					viewReuestDataPanel.buildTabel(columnNames,tableData);
					setListenerToViewDataPanel(viewReuestDataPanel);
					viewReuestDataPanel.getBtnOpenFile().addActionListener(this);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To Continue you must Choose Reuquest",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
					
			}
			else if (e.getSource() == viewReuestsTablePanel.btnRefresh)
			{	
				showAllRequests();
			}
			
		}
		if(viewReuestDataPanel != null)
		{
			if (e.getSource() == viewReuestDataPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(viewReuestsTablePanel);
			}
			else if (e.getSource() == viewReuestDataPanel.btnNext)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if(e.getSource() == viewReuestDataPanel.getBtnOpenFile())
			{
				PDFfile file = chosenReq.getFile();
				if(file!=null)
				{
					new PDFDocument(file, "DateFileFromReq" + chosenReq.getRequestId());
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To This Reuquest There Is Not Data File",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		
		
	}
	
	/**
	 * @param e
	 */
	private void nominateListener(ActionEvent e) 
	{
		if (nominatePanel!=null){
			if (e.getSource() == nominatePanel.btnBack){
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == nominatePanel.btnSubnit)
		{	
			if(nominatePanel.isChosen() )
			{
				SwingWorker worker = new SwingWorker<Void, Void>() {
					@Override
					 public Void doInBackground() 
					 {
						ArrayList<Request> selectedTable;
						int rownum;
						if (nominatePanel.getTabbedPane().getSelectedIndex()==0 )
						{
							rownum = nominatePanel.getChosen();
							selectedTable =requestsToNominate;
						}
						else
						{
							rownum = nominatePanel.getChosen2();
							selectedTable =requestsToreNominate;
						}
						
						int requestid =  selectedTable.get(rownum).getRequestId();
						String ChairMen = (String) nominatePanel.getComboBoxChairMen().getSelectedItem();
						String CommiteMem1 = (String) nominatePanel.getComboBoxMember1().getSelectedItem();
						String CommiteMem2 = (String) nominatePanel.getComboBoxMember2().getSelectedItem();
						String Inspector = (String) nominatePanel.getComboBoxInspector().getSelectedItem();
						int[] Ids = {requestid,Integer.parseInt((ChairMen.split("\\)")[0])),Integer.parseInt((CommiteMem1.split("\\)")[0])),
								Integer.parseInt((CommiteMem2.split("\\)")[0])),Integer.parseInt((Inspector.split("\\)")[0]))};
						if (Ids[1]!=Ids[2] && Ids[1]!=Ids[3]&& Ids[2]!=Ids[3])
							RequestManager.getInstance().AddSaffToReuqest(Ids);
						else{
							JOptionPane.showMessageDialog(new JFrame(),"Opps!, Something went wrong and there is multplicity with the commite members please change the names \n in the combobox", "",JOptionPane.DEFAULT_OPTION);
							return null;
						}
						System.out.println("end of updates");
						return null;
					 }
					public void done(){
						GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
						//nominatePanel.revalidate();
						//nominatePanel.repaint();
					}};
					worker.execute();
			//	nominateComAndInsPane = new NominateCommitteeAndInspectorPanel();
				//GlobalData.guiMangaer.switchScreen(nominateComAndInsPane);
			//	setListenerToInputPanel(nominateComAndInsPane);
				//nominateComAndInsPane.setdata(closeRequestTableListPanel.getChosen() + "");
			}
			else
			{
				//user did not choose any request 
				JOptionPane.showMessageDialog(new JFrame(),"To Continue you must Choose Reuquest", "",JOptionPane.DEFAULT_OPTION);
			}			
		}
	}
	}
	/**
	 * @param e
	 */
	private void addNewInfoSystemListener(ActionEvent e) {
		if(addNewInfoSysPanel !=null)
		{
		    if (e.getSource() == addNewInfoSysPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == addNewInfoSysPanel.btnSubnit)
			{	
				if(addNewInfoSysPanel.isChosen())
				{
					String infoSysName = addNewInfoSysPanel.getInfoSysName();
					if(infoSysName.length()>0)
					{
						String description = addNewInfoSysPanel.getDescription();
						System.out.println("Chosen " + addNewInfoSysPanel.getChosen());
						System.out.println("Chosen worker id " + workerlist.get(addNewInfoSysPanel.getChosen()).getId());
						System.out.println("Chosen worker name " + workerlist.get(addNewInfoSysPanel.getChosen()).getFirstName());
						System.out.println("Chosen worker last name " + workerlist.get(addNewInfoSysPanel.getChosen()).getLastName());
						InfoSystem infoSys = new InfoSystem(infoSysName, description,workerlist.get(addNewInfoSysPanel.getChosen()));
						System.out.println(infoSys.getName() + " " + infoSys.getDescription());
						infoSys.setNewInfoSystemInDb();
						GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
					}
					else
					{
						JOptionPane.showMessageDialog(new JFrame(),"To Continue you must Insert Info Sys Name", "",JOptionPane.DEFAULT_OPTION);
					}
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),"To Continue you must Choose Worker", "",JOptionPane.DEFAULT_OPTION);
				}
			}
		    
		    
		}
	}
	/**
	 * @param e
	 */
	private void resumeRequestListener(ActionEvent e) 
	{
		if(resumeRequestTableListPanel != null)
		{
			if (e.getSource() == resumeRequestTableListPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == resumeRequestTableListPanel.btnNext)
			{	
				if(resumeRequestTableListPanel.isChosen())
				{
					resumeRequestPanel = new ResumeRequestPanel();
					GlobalData.guiMangaer.switchScreen(resumeRequestPanel);
					
					int i = resumeRequestTableListPanel.getChosen();
					chosenReq = requestlist.get(i);;

					resumeRequestPanel.setDateOfCreation(chosenReq.getDate().toString());
					resumeRequestPanel.setInfoSystemName(chosenReq.getInfoSystem().getName());
					resumeRequestPanel.setInitatorName(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
					resumeRequestPanel.setCurrentState(chosenReq.getCurrentState());
					resumeRequestPanel.setProposedChangs(chosenReq.getDescription());
					resumeRequestPanel.setExcuse(chosenReq.getExecuse());
					resumeRequestPanel.setNote(chosenReq.getNotes());
					
					List<RequestStatusHistory> historyList = chosenReq.getHistory();
					System.out.println(" historyList.size() : " + historyList.size());
					
					//Build table for the History Of the request list.
					tableData =  new String[historyList.size()][historyList.get(0).dataToStringArray().length];
					for(int j=0; j<tableData.length ; j++)
					{
						tableData[j] = historyList.get(j).dataToStringArray();
					}
					columnNames = historyList.get(0).indexStringArray();
					resumeRequestPanel.buildTabel(columnNames,tableData);
					setListenerToInputPanel(resumeRequestPanel);
					resumeRequestPanel.getBtnOpenFile().addActionListener(this);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To Continue you must Choose Reuquest",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
			}
			else if (e.getSource() == resumeRequestTableListPanel.btnRefresh)
			{	
				resumeRequest();
			}
		}
		if(resumeRequestPanel!=null)
		{
			if (e.getSource() == resumeRequestPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(resumeRequestTableListPanel);
			}
			else if (e.getSource() == resumeRequestPanel.btnSubnit)
			{	
				if( chosenReq.resume(1) )
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"The Reuquest Is Now Open again",
							"",
							JOptionPane.INFORMATION_MESSAGE);
					GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"There is a problem resume the request, try again later.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
			}
			else if(e.getSource() == resumeRequestPanel.getBtnOpenFile())
			{
				PDFfile file = chosenReq.getFile();
				if(file!=null)
				{
					new PDFDocument(file, "DateFileFromReq" + chosenReq.getRequestId());
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To This Reuquest There Is Not Data File",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		
	}
	/**
	 * @param e
	 */
	private void addWorkerListener(ActionEvent e) 
	{
		if (addworkerscreen!=null)
		{
			if (e.getSource() == addworkerscreen.btnBack)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == addworkerscreen.btnSubnit){
				 
				SwingWorker worker = new SwingWorker<Void, Void>() {
					@Override
					 public Void doInBackground() 
					 {
						//  
						String s  = (String) addworkerscreen.getComboBoxPos().getSelectedItem();
						String[] roll = s.split("\\-");
						boolean succed = WorkerManager.getInstance().addNewWorker(addworkerscreen.getTextFieldID().getText(), roll[1]);
						if (succed == true){
							JOptionPane.showMessageDialog(new JFrame(),"The worker added succesfuly", "",JOptionPane.DEFAULT_OPTION);
						}
						else
						{
							JOptionPane.showMessageDialog(new JFrame(),"The worker didnot added plese try again", "",JOptionPane.DEFAULT_OPTION);
						}
						return null;
					 }
					public void done(){
						
							GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
					}
				};
				worker.execute();
			}
		}
	}
	
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public void statisticalReports()
	{
		   statisticalReportPanel = new SatisticalReportPanel();
		allActivityReport = ReportManager.getInstance().getAllActivityReports();
		for (Report activity : allActivityReport)
		{
			statisticalReportPanel.getComboBoxPastReports().addItem(activity.getComment());
		}
		GlobalData.guiMangaer.switchScreen(statisticalReportPanel);
		setListenerToInputPanel(statisticalReportPanel);
		statisticalReportPanel.addlisteners(this);
		
		
		
	}
	
	public void nominateNewComiteeAndInspector()
	{
		
		 requestsToreNominate = RequestManager.getInstance().getAllRequestsByStatus(new Status(RequestStepStatusEnum.NOMINATED,RequestMainStatusEnum.OPEN));
		 requestsToNominate = RequestManager.getInstance().getUnNominatedRequests();
		if (requestsToNominate.size() == 0 && requestsToreNominate.size() ==0)
		{
			JOptionPane.showMessageDialog(new JFrame(),"There are no new requests to intilize", "",JOptionPane.DEFAULT_OPTION);
			return;
		}
		/*
		 * construct the table by the relevant fields
		 * 
		 */
		
		String[] columnNames = { "Request Id", "Date of Finish", "status", "Command" };
		String[][] tableData =  {{"1",     "avi",     "done"    , "11234" },
								{ "15",   "siete",   "done"  , "333333"}};
		
		if (requestsToNominate.size()>0)
		{
		tableData =  new String[requestsToNominate.size()][requestsToNominate.get(0).dataToStringArray().length];

		for(int i=0; i<tableData.length ; i++)
		{
			tableData[i] = requestsToNominate.get(i).dataToStringArray();
		}
		columnNames = requestsToNominate.get(0).indexStringArray();
		}
		 String[] columnNames2 = { "Request Id", "Date of Finish", "status", "Command" };
			String[][]  tableData2 =  {{"1",     "avi",     "done"    , "11234" },
					{ "15",   "siete",   "done"  , "333333"}};
		
		if (requestsToreNominate.size()>0)
		{
		
			
		
			tableData2 =  new String[requestsToreNominate.size()][requestsToreNominate.get(0).dataToStringArray().length];

			for(int i=0; i<tableData2.length ; i++)
			{
				tableData2[i] = requestsToreNominate.get(i).dataToStringArray();
			}
			columnNames2 = requestsToreNominate.get(0).indexStringArray();
		}	
		//unnominateCommAndInspRequestTableListPanel = new RequestTableListPanel();
		//GlobalData.guiMangaer.switchScreen(unnominateCommAndInspRequestTableListPanel);
	//	unnominateCommAndInspRequestTableListPanel.buildTabel(columnNames,tableData);
	//	setListenerToViewDataPanel(unnominateCommAndInspRequestTableListPanel);	
		
		nominatePanel = new NominateCommitteeAndInspectorPanel();
		
		setListenerToInputPanel(nominatePanel);
		if (requestsToNominate.size()>0)
		{
			nominatePanel.buildTabel(columnNames,tableData);
		}
		if (requestsToreNominate.size()>0)
		{
			nominatePanel.buildTabel2(columnNames2, tableData2);
		}
		
		SwingWorker worker1 = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {
				ArrayList<Worker> lst = new ArrayList<Worker>();
				 workers =  WorkerManager.getInstance().getAllWorkers();
				 for(Worker wo : workers)
				 {
					 if (wo.getRole().compareTo(WorkerRolls.ICM_MANGER)==0)
						 lst.add(wo);
				 }
				 for (Worker wo : lst)
				 {
					 workers.remove(wo);
				 }
				 workersIE = WorkerManager.getInstance().getIEWorkers();
				 int flag=0;
				 for (Worker work : workersIE){
					 nominatePanel.addItemToComboBoxCommitte1(""+work.getId()+") "+work.getFirstName()+" "+work.getLastName());
					 nominatePanel.addItemToComboBoxInspector(""+work.getId()+") "+work.getFirstName()+" "+work.getLastName());
				 }
				// workers.remove(nominatePanel.getComboBoxMember1().getSelectedItem());
				 workers.remove(0);
				 for (Worker work : workers){
					
					
						 nominatePanel.addItemToComboBoxCommitte2(""+work.getId()+") "+work.getFirstName()+" "+work.getLastName());
					 	
					
						
				 }
				// workers.remove(nominatePanel.getComboBoxMember1().getSelectedItem());
				 //workers.remove(nominatePanel.getComboBoxMember2().getSelectedItem());
				 workers.remove(0);
				 for (Worker work : workers){
						
						
					 nominatePanel.addItemToComboBoxChairMen(""+work.getId()+") "+work.getFirstName()+" "+work.getLastName());
				 }
				// workersIE.add((Worker) nominatePanel.getComboBoxMember1().getSelectedItem());
				 workers.add((Worker) nominatePanel.getComboBoxMember2().getItemAt(0));
				 workers.add((Worker) nominatePanel.getComboBoxMember1().getItemAt(0));
				// nominatePanel.getComboBoxMember2().removeItemAt(0);
				// nominatePanel.getComboBoxChairMen().removeItemAt(0);
				// nominatePanel.getComboBoxChairMen().removeItemAt(1);
				 selcted1 = nominatePanel.getComboBoxMember1().getSelectedItem();
				 selcted2 = nominatePanel.getComboBoxMember2().getSelectedItem();
				 selcted3 = nominatePanel.getComboBoxChairMen().getSelectedItem();
				 System.out.println(selcted1+" "+selcted2 +" "+selcted3);
				return null;
			 }
			public void done(){
				//System.out.println("nominateNewComiteeAndInspector not all implemented");
				GlobalData.guiMangaer.switchScreen(nominatePanel);
				
			}
		};
		worker1.execute();
		nominatePanel.getComboBoxMember1().addItemListener(this);
		nominatePanel.getComboBoxMember2().addItemListener(this);
		nominatePanel.getComboBoxChairMen().addItemListener(this);
		
	}
	


	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GuiManager guiMangaer = new GuiManager();
					guiMangaer.showFrame();
					guiMangaer.showHelpAndUserPanel();
					GlobalData.guiMangaer = guiMangaer;
					WorkerPanel workpanel = new WorkerPanel();
					GlobalData.mainScreen = workpanel;
					ICMManagerController.getInstance().resumeRequest();				
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
		if (addworkerscreen!=null){
			if (e.getSource() ==  addworkerscreen.getComboBoxUserDetails()){
			String id = (String) addworkerscreen.getComboBoxUserDetails().getSelectedItem();
			String[] sid = id.split("\\)");
			addworkerscreen.setTextTotextFieldID(sid[0]);
		}
			
		}
		if (nominatePanel!=null){
			if (e.getSource()  == nominatePanel.getComboBoxMember1() && e.getStateChange() == ItemEvent.SELECTED){
				System.out.println("1 "+selcted1 + " ======  "+nominatePanel.getComboBoxMember1().getSelectedItem());
				nominatePanel.getComboBoxMember2().removeItem(nominatePanel.getComboBoxMember1().getSelectedItem());
				nominatePanel.getComboBoxChairMen().removeItem(nominatePanel.getComboBoxMember1().getSelectedItem());
				//nominatePanel.getComboBoxMember2().addItem(selcted1);
				
				//selcted1 = nominatePanel.getComboBoxMember1().getSelectedItem();
				if (selcted1 != nominatePanel.getComboBoxMember1().getSelectedItem())
				{
					if (selcted1!=null){
						nominatePanel.getComboBoxMember2().addItem(selcted1);
						nominatePanel.getComboBoxChairMen().addItem(selcted1);
					}
					selcted1 = nominatePanel.getComboBoxMember1().getSelectedItem();
				}
				//nominatePanel.getComboBoxMember2().removeItem("");
				//nominatePanel.getComboBoxMember1().removeItem("");
			}
			else if (e.getSource()  == nominatePanel.getComboBoxMember2() && e.getStateChange() == ItemEvent.SELECTED){
				System.out.println("2 "+ selcted2 + " ======  "+nominatePanel.getComboBoxMember2().getSelectedItem());
				nominatePanel.getComboBoxMember1().removeItem(nominatePanel.getComboBoxMember2().getSelectedItem());
				nominatePanel.getComboBoxChairMen().removeItem(nominatePanel.getComboBoxMember2().getSelectedItem());
				//nominatePanel.getComboBoxMember1().addItem(selcted2);
				if (selcted2 != nominatePanel.getComboBoxMember2().getSelectedItem())
				{
					if (selcted2!=null){
						nominatePanel.getComboBoxMember1().addItem(selcted2);
						nominatePanel.getComboBoxChairMen().addItem(selcted2);
					}
					selcted2 = nominatePanel.getComboBoxMember2().getSelectedItem();
				}
			//	nominatePanel.getComboBoxMember2().removeItem("");
			//	nominatePanel.getComboBoxMember1().removeItem("");
			}
			else if (e.getSource()  == nominatePanel.getComboBoxChairMen() && e.getStateChange() == ItemEvent.SELECTED){
				System.out.println("3 "+selcted3 + " ======  "+nominatePanel.getComboBoxChairMen().getSelectedItem());
				nominatePanel.getComboBoxMember1().removeItem(nominatePanel.getComboBoxChairMen().getSelectedItem());
				nominatePanel.getComboBoxMember2().removeItem(nominatePanel.getComboBoxChairMen().getSelectedItem());
				//nominatePanel.getComboBoxMember1().addItem(selcted2);
				if (selcted3 != nominatePanel.getComboBoxChairMen().getSelectedItem())
				{
					if (selcted3!=null){
						nominatePanel.getComboBoxMember1().addItem(selcted3);
						nominatePanel.getComboBoxMember2().addItem(selcted3);
					}
					selcted3 = nominatePanel.getComboBoxChairMen().getSelectedItem();
				}
			//	nominatePanel.getComboBoxMember2().removeItem("");
				//nominatePanel.getComboBoxMember1().removeItem("");
			}
		}
		
			
	}
	
	
	
}
